/**
 * 
 */
package com.education;

import java.io.IOException;
import java.io.InputStream;
import java.util.BitSet;
import java.util.Random;

import org.andengine.ui.activity.SimpleBaseGameActivity;

import android.content.Context;
import android.widget.Toast;

/**
 * @author iastepanov
 *
 */
public class Utilities {
	
	//abstract + final
	private Utilities() {
	    throw new AssertionError();
	}
	
	public static String loadJSONFromAsset(Context context, String jsonFile) {
        String json = null;
        try {

            InputStream is = context.getAssets().open(jsonFile);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }
	
	// Implementing Fisher–Yates shuffle
	public static int[] shuffle(int length)
	{
		int[] ar = new int[length];
		for (int i=0;i<length;i++)
		{
			ar[i]=i;
		}
		Random rnd = new Random();
		for (int i = ar.length - 1; i >= 0; i--)
		{
			int index = rnd.nextInt(i + 1);
			//Simple swap
			int a = ar[index];
			ar[index] = ar[i];
			ar[i] = a;
		}
		return ar;
	}
  
	//http://stackoverflow.com/questions/6171663/how-to-find-index-of-int-array-in-java-from-a-given-value
	public static int getIndexOf( int search, int[] array )
	{
		for( int i=0; i< array.length ; i ++ )
			if( array[ i ] == search)
				return i;
		return -1;
	}
  
	public static void showToastFromBackground(final String message, final SimpleBaseGameActivity activity ) {
		activity.runOnUiThread(new Runnable() {
    		@Override
    		public void run() {
    			Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
    		}
    	});
	}
	
	public static BitSet bitSetFromLong(long value) {
	    BitSet bits = new BitSet();
	    int index = 0;
	    while (value != 0L) {
	      if (value % 2L != 0) {
	        bits.set(index);
	      }
	      ++index;
	      value = value >>> 1;
	    }
	    return bits;
	  }
}
